import {
  indexPaginateBuilder,
  showBuilderEntity,
} from '@libs/common/repository';
import { Inject, Injectable } from '@nestjs/common';
import {
  Equal,
  FindOptionsSelect,
  FindOptionsWhere,
  IsNull,
  Not,
  Repository,
} from 'typeorm';

import { FindMemberDto, MemberIndexDto, ShowMemberDto } from './dto/member.dto';
import { Member } from './entities/member.entity';
import { ProviderKey } from './member.providers';
@Injectable()
export class MemberService {
  @Inject(ProviderKey)
  private repository: Repository<Member>;

  async index(dto: MemberIndexDto) {
    const res = await indexPaginateBuilder({
      dto,
      repository: this.repository,
    });

    return res;
  }

  show<D extends ShowMemberDto = ShowMemberDto>(dto: D) {
    return showBuilderEntity(this.repository, dto);
  }

  /** 只返回一条对象数据，如果存在多个只返回第一条 */
  async findOne(dto: FindMemberDto, select?: FindOptionsSelect<Member>) {
    const entity = await this.findBase(dto, select);

    if (Array.isArray(entity) && entity.length > 0) {
      return entity[0];
    }

    return null;
  }

  /** 返回所有符合条件的数据 */
  find(dto?: FindMemberDto, select?: FindOptionsSelect<Member>) {
    return this.findBase(dto || {}, select);
  }

  private findBase(dto: FindMemberDto, select?: FindOptionsSelect<Member>) {
    const where: FindOptionsWhere<Member> = dto;

    return this.repository.find({ where, select });
  }

  /** 查询所有钉钉ID */
  async findDingId(dto?: { status?: 0 | 1 }) {
    const where: FindOptionsWhere<Member> = {
      status: dto?.status ?? 1,
    };

    const idList = await this.repository.find({
      where,
      select: ['dingUserId'],
    });

    return idList.map((v) => v.dingUserId);
  }

  async findByName(name: string) {
    if (!name) return [];
    return this.repository.findBy({
      name: Equal(name),
      userId: Not(IsNull()),
    });
  }
}
